package GUI;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import javax.swing.AbstractListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JScrollPane;
import javax.swing.JScrollBar;
import javax.swing.JLabel;
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;
import javax.swing.UIManager;

import java.awt.Font;
import java.awt.Color;

import javax.swing.JTextField;
import javax.swing.JButton;

import UserData.UserInformation;
import UserData.User_Info;
import UserData.User_Management;

import com.toedter.calendar.JCalendar;
import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JDateChooserBeanInfo;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTable;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.BevelBorder;
import javax.swing.JRadioButton;


public class NormalUser extends JFrame {

   /**
    * Main.
    */
   public static void main(String[] args) {
      EventQueue.invokeLater(new Runnable() {
         public void run() {
            try {
               NormalUser frame = new NormalUser();
               frame.setVisible(true);
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      });
   }

   /**
    * Variable.
    */
   private JPanel contentPane;
   private JTabbedPane tabbedPane;
   private JPanel panelMain;
   private JButton btnMain;
   private JLabel lblCurrentTime;
   private JLabel lblNextMeeting;
   private JPanel panelMyPage;
   private JPanel panelGraph;
   private JPanel panel;
   private JPanel panelCompare;
   private JScrollPane scrollPaneShowFriends;
   private JScrollBar scrollBar;
   private JLabel lblMyFriends;
   private JLabel lblTerm;
   private JDateChooser endDateChooser;
   private JDateChooser startDateChooser;
   private JButton btnEnter;
   private JLabel lblStartDay;
   private JLabel lblEndday;
   private JTextField txtfMPSearch;
   private JTable table;
   private JScrollPane scrollPane;
   private JList list;
   private Object[][] data;
   private JCheckBox checkBoxFriend;
   private JCheckBox checkBoxFriend1;
   private JTextField txtfEntername;
   private JButton btnEntername;
   private String MPSearchStr;
   private String MPSearchlowstr;
   private String MPSearchupstr;
   private String samestr;
   private Calendar cal;
   private int day;
   private int mon;
   private int lastday;
   private String[] whatday;
   private boolean MPflag;
   private int[][] temp;

   private void initVar(){


      contentPane = new JPanel(){
         @Override
         public void paintComponent(Graphics g){
            Image image = new ImageIcon("normaluser.png").getImage();
            g.drawImage(image, 0, 0, this);
         }      
      };
      tabbedPane = new JTabbedPane(SwingConstants.TOP)/*{
         public void paintComponent(Graphics g){
            Image image = new ImageIcon("tabbbbbbbbbb.png").getImage();///////////////////////////
            g.drawImage(image, 0, 0, this);
         }      
      }*/;
      tabbedPane.setBorder(null);
      panelMain = new JPanel();
      panelMain.setBorder(null);
      btnMain = new JButton("Button"){
          public void paintComponent(Graphics g){
              Image image = new ImageIcon("car.png").getImage();///////////////////////////
              g.drawImage(image, 0, 0, this);
           }      
        };
      btnMain.setBorder(null);
      btnMain.addActionListener(new ActionListener() {
      	public void actionPerformed(ActionEvent arg0) {
      	}
      });
      lblCurrentTime = new DigitalClock();
      lblCurrentTime.setFont(new Font("Impact", Font.PLAIN, 50));
      lblNextMeeting = new JLabel("Next Meeting");
      panelMyPage = new JPanel();
      panelMyPage.setBorder(null);
      panelGraph = new JPanel();
      panelGraph.setBorder(null);
      panel = new JPanel();      
      panelCompare = new JPanel();
      panelCompare.setBorder(null);
      scrollPaneShowFriends = new JScrollPane();
      scrollPaneShowFriends.setBounds(47, 69, 265, 377);
      scrollBar = new JScrollBar();
      lblMyFriends = new JLabel("My Friends");
      lblMyFriends.setBounds(47, 35, 137, 35);
      lblTerm = new JLabel("Term");
      lblTerm.setBounds(336, 87, 63, 35);
      btnEnter = new JButton("Enter"){
         
         public void paintComponent(Graphics g){
            Image image = new ImageIcon("iconenter.png").getImage();
            g.drawImage(image, 0, 0, this);
         }      
      };
      btnEnter.setBounds(568, 326, 80, 40);
      btnEnter.setBorder(null);
      lblStartDay = new JLabel("StartDay");
      lblStartDay.setForeground(Color.GRAY);
      lblStartDay.setBounds(336, 132, 57, 15);
      lblEndday = new JLabel("EndDay");
      lblEndday.setForeground(Color.GRAY);
      lblEndday.setBounds(336, 216, 57, 15);
      endDateChooser = new JDateChooser();
      endDateChooser.setBounds(336, 235, 220, 40);
      //endDateChooser.getCalendarButton().setIcon(new ImageIcon("C:\\Users\\Youngchae\\workspace\\OOP_Team4_Project\\iconmain.png"));
      endDateChooser.getCalendarButton().setBorder(null);
      endDateChooser.setBorder(null);
      startDateChooser = new JDateChooser();
      startDateChooser.setBounds(336, 149, 220, 40);
      //startDateChooser.getCalendarButton().setIcon(new ImageIcon("C:\\Users\\Youngchae\\workspace\\OOP_Team4_Project\\iconmain.png"));
      startDateChooser.getCalendarButton().setBorder(null);
      startDateChooser.setBorder(null);
      UserInformation userJbox = new UserInformation();

      String checkBoxName = userJbox.getName();
      checkBoxFriend1 = new JCheckBox(checkBoxName);
      scrollPaneShowFriends.setColumnHeaderView(checkBoxFriend1);

      
      
      startDateChooser.getCalendarButton().addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
         }
      });







      contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
      setContentPane(contentPane);
      contentPane.setLayout(null);


      tabbedPane.setBounds(50, 40, 730, 500);
      contentPane.add(tabbedPane);


      Icon tabmain = new ImageIcon("tabmain.png");
      Icon tabmypage = new ImageIcon("tabmypage.png");
      Icon tabgraph = new ImageIcon("tabgraph.png");
      Icon tabcompare = new ImageIcon("tabcompare.png");

      tabbedPane.addTab("", tabmain, panelMain, null);
      panelMain.setLayout(null);


      btnMain.setBounds(249, 307, 250, 100);//if(占쏙옙占썲가占쏙옙占쏙옙擔챨占�-15<占쏙옙占쏙옙챨占�&&占쏙옙튼占쏙옙 占싼뱄옙占쏙옙 占쏙옙占쏙옙占쏙옙 占십억옙占쏙옙占쏙옙){  btnMain enable } 
      panelMain.add(btnMain);



      lblCurrentTime.setBounds(287, 70, 237, 100);
      panelMain.add(lblCurrentTime);

      lblNextMeeting.setBounds(319, 198, 97, 39);
      panelMain.add(lblNextMeeting);

      /**
       * Start My Page.
       */

      cal = Calendar.getInstance();
      cal.get(Calendar.DAY_OF_MONTH);
      mon = cal.get(Calendar.MONTH)+1;
      lastday=cal.getActualMaximum(Calendar.DATE);
      whatday=new String[lastday];
      temp =new int[lastday][48];

      for(int i=0;i<lastday;i++){
         whatday[i]=mon+"/"+(i+1);
      }

      tabbedPane.addTab("", tabmypage, panelMyPage, null);
      panelMyPage.setLayout(null);

      txtfMPSearch = new JTextField();
      txtfMPSearch.setBorder(null);
      txtfMPSearch.setBounds(421, 30, 180, 40);
      panelMyPage.add(txtfMPSearch);
      txtfMPSearch.setColumns(10);

      JButton btnMPSearch = new JButton("Search"){
          public void paintComponent(Graphics g){
              Image image = new ImageIcon("iconsearch.png").getImage();///////////////////////////
              g.drawImage(image, 0, 0, this);
           }      
        };
      btnMPSearch.setBorder(null);
      btnMPSearch.setBounds(610, 29, 80, 40);
      btnMPSearch.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent arg0) {   
            
        	SerchActionPerformed(arg0);  
        	 
        	 
        	 
        	 
        	            }	

      });
      panelMyPage.add(btnMPSearch);
      
      data = new Object[lastday][48];
      data[0][0] = "GAME";
      data[2][5] = "TV";
      data[5][3] = "DRAMA";
      data[3][3] = "TV";
      
      DefaultTableModel dm = new DefaultTableModel(data,whatday);

      
      scrollPane = new JScrollPane();
      scrollPane.setBounds(12, 80, 679, 370);
      panelMyPage.add(scrollPane,BorderLayout.CENTER);

      table = new JTable(dm){
    	  
    	  private final Color grayColor1 = new Color(223, 223, 223);
          private final Color grayColor2 = new Color(207, 207, 207);
          public Component prepareRenderer(TableCellRenderer tcr, int row, int column) {
            Component c = super.prepareRenderer(tcr, row, column);
            if(MPflag==true){
                c.setBackground(Color.red);
              }
            else {
                c.setBackground((row%2==0)?grayColor1:grayColor2);
                }
                
            return c;
          }
    	  
    	  

         @Override
         public boolean isCellEditable(int row, int column) {
            return false;
         }


      };

      table.setRowHeight(50);
      table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
      table.setColumnSelectionAllowed(true);
      table.setRowSelectionAllowed(true);

      DefaultTableCellRenderer tScheduleCellRenderer = new DefaultTableCellRenderer();
      tScheduleCellRenderer.setHorizontalAlignment(SwingConstants.CENTER);
      TableColumnModel tcmSchedule = table.getColumnModel();
      for (int i = 0; i < tcmSchedule.getColumnCount(); i++) {
    	  tcmSchedule.getColumn(i).setCellRenderer(tScheduleCellRenderer);
    	  }
      scrollPane.setViewportView(table);

      
      list = new JList(new AbstractListModel() {
         String[] values = new String[] {"09:00~09:30", "09:30~10:00", "10:00~10:30", "10:30~11:00", "11:00~11:30", "11:30~12:00", "12:00~12:30", "12:30~13:00", "13:00~13:30", "13:30~14:00", "14:00~14:30", "14:30~15:00", "15:00~15:30", "15:30~16:00", "16:00~16:30", "16:30~17:00", "17:00~17:30", "17:30~18:00", "18:00~18:30", "18:30~19:00", "19:00~19:30", "19:30~20:00", "20:00~20:30", "20:30~21:00", "21:00~21:30", "21:30~22:00"};
         public int getSize() {
            return values.length;
         }
         public Object getElementAt(int index) {
            return values[index];
         }
      });

      list.setFixedCellWidth(100);
      list.setFixedCellHeight(50);
      list.setCellRenderer(new RowHeaderRenderer(table));
      scrollPane.setRowHeaderView(list);
      
      JLabel lbSubject = new JLabel("Subject");
      lbSubject.setBounds(339, 30, 49, 29);
      panelMyPage.add(lbSubject);

      /**
       *  Cell Mouseclick and regisration.
       */

      table.addMouseListener(new MouseAdapter(){
         @Override
         public void mouseClicked(MouseEvent e){
            if(e.getClickCount()==2){
               double row = table.rowAtPoint(e.getPoint());
               System.out.println("row:" + row);
               if(row%2==0){ 
                  row = row/2+9; //time 9,10,11,....
               }
               else{
                  row = (int)row/2+9.5; //time 9.5,10.5,11.5,....
               }
               int col = table.columnAtPoint(e.getPoint());
               col = col+1; //date
               
               String source = null;//double 타입인 row 와 col을 Date 타입으로 바꾸기 위해 선언한 변수
               int intRow=(int)row;
               System.out.println("row:" + row + "  intRow:"+intRow);
               if(row-intRow==0.0){
            	   source="2014-12-"+col+"-"+intRow+"-"+"00";
               }else if(row-intRow==0.5){
            	   source="2014-12-"+col+"-"+intRow+"-"+"30";
               }
               System.out.println("마이페이지배열에서 받은 날짜를 date형으로 변환하기 전 잠시 가지고 있는 source: "+source);
               SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-HH-mm");
               Date date = null;
               try {
					date = sdf.parse(source);
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					System.out.println("NormalUser 클래스에서 나의 스케줄 추가할때 double 을 date로 바꿀때 에러");
				}
               System.out.println("source를 date형으로 변환한 값:" + date);
               
               Registration register = new Registration();
               register.getDateChooser().setDate(date);
               register.getCmbStartHour().setSelectedIndex(intRow-9);
               if(row-intRow==0.5){
            	   register.getCmbStartMin().setSelectedIndex(1);
            	   register.getCmbFinishHour().setSelectedIndex(intRow-8);
            	   register.getCmbFinishMin().setSelectedIndex(0);
               }else if(row-intRow==0){
            	   register.getCmbStartMin().setSelectedIndex(0);
            	   register.getCmbFinishHour().setSelectedIndex(intRow-9);
            	   register.getCmbFinishMin().setSelectedIndex(1);
               }
               
               register.setVisible(true);

           //    register.repaint();
               

               //contentPane.setVisible(false);
            }
         }
      });


      /**
       * End My Page.
       */


      tabbedPane.addTab("", tabgraph, panelGraph, null);
      panelGraph.setLayout(null);

      panel.setBounds(35, 49, 505, 196);
      panelGraph.add(panel);
      panelCompare.setLayout(null);


      tabbedPane.addTab("", tabcompare, panelCompare, null);
      panelCompare.add(scrollPaneShowFriends);

      scrollPaneShowFriends.setRowHeaderView(scrollBar);
      
      JPanel panel_1 = new JPanel();
      scrollPaneShowFriends.setViewportView(panel_1);
      panel_1.setLayout(null);
      //String checkBoxName = userJbox.getName();
      
      //User_Info user = new User_Info();
      User_Management userManage = new User_Management();
      
      for(int i = 0; i<userManage.Get_User_list.size(); i++){
      
      JCheckBox checkBoxFriend = new JCheckBox(User_Management.Get_User_list.get(i).getUser_Real_Name());
      checkBoxFriend.setBounds(0, 25*i, 118, 23);
      panel_1.add(checkBoxFriend);	
      
      }
      
      //JCheckBox chckbxNewCheckBox = new JCheckBox("Kim Tae Hoon");
      //chckbxNewCheckBox.setBounds(0, 25, 118, 23);
      //panel_1.add(chckbxNewCheckBox);
      
      lblMyFriends.setForeground(Color.DARK_GRAY);
      lblMyFriends.setFont(new Font("占쏙옙占쏙옙 占쏙옙占�", Font.PLAIN, 20));
      panelCompare.add(lblMyFriends);

      lblTerm.setForeground(Color.DARK_GRAY);
      lblTerm.setFont(new Font("占쏙옙占쏙옙 占쏙옙占�", Font.PLAIN, 20));
      panelCompare.add(lblTerm);

      btnEnter.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {

            EnterActionPerformed(e);
         }
      });
      panelCompare.add(btnEnter);
      panelCompare.add(lblStartDay);
      panelCompare.add(lblEndday);
      panelCompare.add(startDateChooser);
      panelCompare.add(endDateChooser);
      
      
      
      
     
      
      
      
      
      btnEntername = new JButton("New button"){
          public void paintComponent(Graphics g){
              Image image = new ImageIcon("fapp.png").getImage();///////////////////////////
              g.drawImage(image, 0, 0, this);
           }      
        };
      btnEntername.setBorder(null);
        
        
      btnEntername.addActionListener(new ActionListener() {
      	public void actionPerformed(ActionEvent e) {
      		System.out.println("txtf");
      		 txtfEntername = new JTextField();  
      		 txtfEntername.setBackground(new Color(255, 255, 255)); 
      		 txtfEntername.setBorder(null);
      		txtfEntername.setToolTipText("appointment name");
      		txtfEntername.setText("");
      		txtfEntername.setDisabledTextColor(Color.WHITE);
      		txtfEntername.setForeground(Color.LIGHT_GRAY);
      		 txtfEntername.setBounds(212, 393, 220, 40);
      		 panelCompare.add(txtfEntername);
      		 txtfEntername.setColumns(10);
      		
      		panelCompare.remove(btnEntername);
      		
      	}
      });
      btnEntername.setBounds(336, 326, 220, 40);
      panelCompare.add(btnEntername);


   
   
   }


   


   /**
    *   RowHeader
    */


   class RowHeaderRenderer extends JLabel implements ListCellRenderer {

      RowHeaderRenderer(JTable table) {
         JTableHeader header = table.getTableHeader();
         setOpaque(true);
         setBorder(UIManager.getBorder("TableHeader.cellBorder"));
         setHorizontalAlignment(CENTER);
         setForeground(header.getForeground());
         setBackground(header.getBackground());
         setFont(header.getFont());
      }

      public Component getListCellRendererComponent(JList arg0, Object arg1,
            int arg2, boolean arg3, boolean arg4) {
         setText((arg1 == null) ? "" : arg1.toString());
         return this;
      }
   }   


   /**
    *   BoardTableCell
    */


   class BoardTableCellRenderer  extends DefaultTableCellRenderer{
      Component c;
      private static final long serialVersionUID = 1L;
      private final Color selectionBlue = new Color(131,166,198);
      private final MatteBorder border = new MatteBorder(1, 1, 0, 0, Color.BLACK);
      @Override
      public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
         c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

         if (table.isCellSelected(row, column)){
            c.setBackground(this.selectionBlue);
            setBorder(this.border);
         }
         else {
            c.setBackground(Color.WHITE);
         }
         return c;
      }
   }







   public NormalUser() {


      initVar();
      setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      setBounds(100, 100, 840, 640);


   }

   
   public void SerchActionPerformed(ActionEvent e){
	   
	   MPSearchStr = txtfMPSearch.getText();
       MPSearchlowstr = MPSearchStr.toLowerCase();
       MPSearchupstr = MPSearchStr.toUpperCase();
       samestr="";
       MPflag =false;
          for(int i=0;i<data.length;i++){
             for(int j=0;j<data[i].length;j++){
                if(MPSearchlowstr.equals(data[i][j])||MPSearchupstr.equals(data[i][j])){
                   temp[i][j]=1;
                	MPflag=true;
                   samestr = "Date: " + mon + "/"+ (j+1)+ "\n"+samestr;
                }
             }
          }
          if(MPflag==false)
             JOptionPane.showMessageDialog(contentPane, "NO FOUND");
          else
        	  
        	  JOptionPane.showMessageDialog(contentPane, samestr);

	   
   }
   

   public void EnterActionPerformed(ActionEvent e){


      if(startDateChooser.getDate() == null || startDateChooser.getDate().equals("")){
         JOptionPane.showMessageDialog(this, "Type your Start Date");
      }

      else if(endDateChooser.getDate() == null || endDateChooser.getDate().equals("")){
         JOptionPane.showMessageDialog(this, "Type your End Date");
      }
      
      else if(checkBoxFriend.isSelected()==false){
    	  JOptionPane.showMessageDialog(this, "Select your friend");
      }
    	  
      
		else {
			Result regi = new Result();
			regi.setVisible(true);
			   String startDate = startDateChooser.getDate().toString();
			   String endDate = endDateChooser.getDate().toString();
			   int start1 = startDate.indexOf(8);
			   int start2 = startDate.indexOf(9);
			   int start = (start1*10+start2);
			   int end1 = endDate.indexOf(8);
			   int end2 = endDate.indexOf(9);
			   int end = (end1*10+end2);
			   System.out.println(startDate);
			   System.out.println(start1);
			   System.out.println(start2);
			   System.out.println(start);
		}
      
   }
   
   public void Comparer(int i, int j){
	   ArrayList<String> user = new ArrayList<String>();
	   if(checkBoxFriend.isSelected()){
		   //Load Friend1's schedule
	   }
	   int sche_array[][] = new int[26][31];
	   //creating i*j array
	   for(i = 0; i<sche_array.length; i++){
		   for(j = 0; j<sche_array.length; j++){
			   //for(){
				   
			   //}
		   }
	   }
	   
   }
   
   public void addFriendList(){
	   
	   User_Management user = new User_Management();
	   
   }
}




